<?php
declare (strict_types=1);

namespace app;

use app\model\User;
use app\traits\JsonResponse;
use Firebase\JWT\BeforeValidException;
use Firebase\JWT\ExpiredException;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use Firebase\JWT\SignatureInvalidException;
use think\App;
use think\exception\ValidateException;
use think\Validate;
use DomainException;
use InvalidArgumentException;
use UnexpectedValueException;
use think\facade\Request as RequestFacade;


/**
 * 控制器基础类
 */
abstract class BaseController {
    use JsonResponse;
    /**
     * Request实例
     * @var \think\Request
     */
    protected $request;

    protected $user_id;
    protected $auth_user;

    /**
     * 应用实例
     * @var \think\App
     */
    protected $app;

    /**
     * 是否批量验证
     * @var bool
     */
    protected $batchValidate = false;

    /**
     * 控制器中间件
     * @var array
     */
    protected $middleware = [];

    /**
     * 构造方法
     * @access public
     * @param App $app 应用对象
     */
    public function __construct(App $app) {
        $this->app = $app;
        $this->request = $this->app->request;

        // 控制器初始化
        $this->initialize();
    }

    // 初始化
    protected function initialize() {
        $jwt = RequestFacade::header('authorization');
        if(empty($jwt)){
            return $this->jsonFail(message:'令牌不能为空');
        }
        $arr = explode(' ',trim($jwt));
        $token = $arr[1];
        try {
            $res = JWT::decode($token, new Key(getSalt(),'HS256'));
            $this->user_id = $res->user_id;
            $user = User::findOrEmpty($res->user_id);
            if(!$user->isEmpty()){
                $this->auth_user = $user;
            }else{
                return $this->jsonFail(message:'获取用户失败');
            }
        } catch (InvalidArgumentException $e) {
            return $this->jsonFail('token error');
        } catch (DomainException $e) {
            return $this->jsonFail('token error');
        } catch (SignatureInvalidException $e) {
            return $this->jsonFail('token error');
        } catch (BeforeValidException $e) {
            return $this->jsonFail('token error');
        } catch (ExpiredException $e) {
            return $this->jsonFail('token 过期');
        } catch (UnexpectedValueException $e) {
            return $this->jsonFail('token error');
        } catch (\Exception $e){
            return $this->jsonFail('token error');
        }
    }

    /**
     * 验证数据
     * @access protected
     * @param array $data 数据
     * @param string|array $validate 验证器名或者验证规则数组
     * @param array $message 提示信息
     * @param bool $batch 是否批量验证
     * @return array|string|true
     * @throws ValidateException
     */
    protected function validate(array $data, string|array $validate, array $message = [], bool $batch = false) {
        if (is_array($validate)) {
            $v = new Validate();
            $v->rule($validate);
        } else {
            if (strpos($validate, '.')) {
                // 支持场景
                [$validate, $scene] = explode('.', $validate);
            }
            $class = false !== strpos($validate, '\\') ? $validate : $this->app->parseClass('validate', $validate);
            $v = new $class();
            if (!empty($scene)) {
                $v->scene($scene);
            }
        }

        $v->message($message);

        // 是否批量验证
        if ($batch || $this->batchValidate) {
            $v->batch(true);
        }

        return $v->failException(true)->check($data);
    }

}
